<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="600px" :title="`${drawerProps.title}文件`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="类型" prop="typeId">
        <el-cascader v-model="drawerProps.typeId" :options="options" :props="defaultOptions" clearable />
      </el-form-item>
      <el-form-item label="文件上传" prop="avatar">
        <UploadSlice :prefix-data="DATA" accept="*" :limit-number="5" @change="successHandle" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="drawerProps.remark" type="textarea" placeholder="请填写备注" clearable :rows="3"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, getCurrentInstance } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { User, Dict, File } from "@/api/interface";
import UploadSlice from "@/components/Upload/UploadSlice.vue";
import { DATA } from "@/constants";
const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;
const rules = reactive({
  typeId: [{ required: true, message: "请选择目录" }]
});

interface DrawerProps {
  title: string;
  isView?: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  getDict?: (params: any) => Promise<any>;
  typeId: string;
  fileList: File.ResFileList[];
  remark: string;
}
const options = ref();
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
  typeId: "",
  remark: "",
  fileList: []
});

let defaultOptions = ref();

const successHandle = (files: any) => {
  drawerProps.value.fileList = files;
};
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  const { data } = await drawerProps?.value.getDict!({ parentId: dict.marketResources });
  data.forEach((item: any) => {
    item.hasChild = !item.hasChild;
  });
  options.value = data;
  defaultOptions.value = {
    lazy: true,
    label: "name",
    value: "id",
    checkStrictly: true,
    lazyLoad: loadNode,
    leaf: "hasChild"
  };
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      const params = drawerProps.value.fileList.map(item => {
        return {
          name: item.name,
          originalFileName: item.originalFileName,
          path: item.path,
          size: item.size,
          typeId: Array.isArray(drawerProps.value.typeId)
            ? drawerProps.value.typeId[drawerProps.value.typeId.length - 1]
            : drawerProps.value.typeId,
          remark: drawerProps.value.remark
        };
      });
      await drawerProps.value.api!(params);
      ElMessage.success({ message: `${drawerProps.value.title}资料成功！` });
      drawerProps?.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
// 加载字典数据
const loadNode = async (node: any, resolve: (data: Dict.ResDictList[]) => void) => {
  if (node.value) {
    const { data } = await drawerProps?.value.getDict!({ parentId: node.value });
    data.forEach((item: any) => {
      item.hasChild = !item.hasChild;
    });
    resolve(data);
  }
};
defineExpose({
  acceptParams
});
</script>
